package com.gzcstec.stmp.factory;

import com.gzcstec.stmp.config.StmpServerConfig;
import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * stmp自定义工厂类
 */
@Component
public class StmpFactory extends BasePooledObjectFactory<Session> {

    private static Logger logger = LoggerFactory.getLogger(StmpFactory.class);
    //邮箱服务器配置信息
    @Autowired
    private StmpServerConfig stmpServerConfig;

    @Override
    public Session create() throws Exception {
        //设置属性
        Properties properties = new Properties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", stmpServerConfig.getServer());
        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(stmpServerConfig.getUsername(), stmpServerConfig.getPassword()); //发件人邮件用户名、密码
            }
        });
        logger.debug("stmp创建session回话链接");
        return session;
    }

    @Override
    public PooledObject<Session> wrap(Session session) {
        return new DefaultPooledObject<Session>(session);
    }

    /**
     * 销毁对象
     */
    @Override
    public void destroyObject(PooledObject<Session> p) throws Exception {
        Session session = p.getObject();
        super.destroyObject(p);
    }

    /**
     * 验证对象
     */
    @Override
    public boolean validateObject(PooledObject<Session> p) {
        //TODO 增加邮箱回话有效性的验证
       return true;
    }
}
